package com.jbm.core.common;

import com.jbm.core.client.PlayCallback;
import com.jbm.core.pb.PBIAcross;

import org.apache.mina.core.buffer.AbstractIoBuffer;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

/**
 * Created by root on 16-10-14.
 */
public class P2PHandler extends IoHandlerAdapter
{
	protected static Logger s_logger = LoggerFactory.getLogger(P2PHandler.class);
	protected PlayCallback m_playcallback;
	protected P2PServer m_p2piface;

	public P2PHandler ( )
	{
	}

	public P2PHandler ( PlayCallback callback )
	{
		m_playcallback = callback;
	}

	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		s_logger.error("p2p client端发送异常...", cause);
	}

	public void messageReceived(IoSession session, Object message) throws Exception {
		AbstractIoBuffer buf = (AbstractIoBuffer) message;
		byte[] pbbuffer;
		PBIAcross.IAcross iacross = null;
		try
		{
			int len = buf.remaining();
			pbbuffer = new byte[len];
			buf.get(pbbuffer);

			iacross = PBIAcross.IAcross.parseFrom(pbbuffer);
		}catch (Exception e)
		{
			s_logger.info("PBParse Error:"+e.getMessage());
			return;
		}


		s_logger.info("data recv..."+iacross.toString());

		if ( AutoCall.g_autocall.Relay(session,iacross,MainServer.g_server.getM_local_id()))
			return;

		if ( ( iacross.getRandr() & RandR.RANDR_TYPE_RESPONSE ) == RandR.RANDR_TYPE_RESPONSE )
		{
			P2PDialog p2pdialog = AutoCall.g_autocall.GetDialog(iacross);
			if (p2pdialog != null)
			{
				s_logger.info("find p2pdialog...");

				p2pdialog.Put(iacross);
			} else
			{
			}
		}

		if ( ( iacross.getRandr() & RandR.RANDR_TYPE_REQUEST ) == RandR.RANDR_TYPE_REQUEST )
		{
			AutoCall.g_autocall.Invoke(session,iacross,MainServer.g_server.getM_local_id());
		}
	}

	public void sessionCreated(IoSession session) throws Exception {
		s_logger.info("客户端与服务端创建连接...port:"+((InetSocketAddress) session.getRemoteAddress()).getPort());
	}

	public void sessionClosed(IoSession session) throws Exception
	{
		ConnectAgent ca = (ConnectAgent)session.getAttribute("CA_Key");

		if ( ca != null )
		{
			ca.Die();
			s_logger.error("P2P client 关闭..."+ca.getM_iaccount().getM_account_id());
		}else
			s_logger.error("P2P client 关闭...");
	}
}
